package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.ThreadLocalUtils;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl  implements LoginService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SystemUserService systemUserService;




    @Override
    public CaptchaVo getCaptcha() {

        /**
         * 生产验证码图片 (生成图片,正确验证码存储到redis)
         *  1. 新的依赖需要导入
         *  2. 修改redis连接的配置 (application.yml)
         *  3. redisTemplate 4个序列化位置需要配置
         *  4. 生成验证码图片和正确验证码
         *  5. 正确验证码存储到redis里
         *  6. 把图片转成base64和rediskey一起装到CaptchaVo
         *  7. 返回CaptchaVo
         */
        SpecCaptcha captcha = new SpecCaptcha(140,38,4);
        captcha.setCharType(SpecCaptcha.TYPE_DEFAULT);
        //把验证码图片转成base64图片
        String imgBase64 = captcha.toBase64();
        //正确验证码
        String text = captcha.text();

        //存储到redis [设置有效期]
        String key = RedisConstant.ADMIN_LOGIN_PREFIX +  UUID.randomUUID().toString();
        // admin:login:xxxxxxxxx  keys admin* admin:login*  xxxxxxxxxx
        redisTemplate.opsForValue().set(key, text , RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS );


        return new CaptchaVo(imgBase64,key);
    }

    @Override
    public String login(LoginVo loginVo) {

        //1. 验证 验证码
        if (StringUtils.isBlank(loginVo.getCaptchaCode())){
            throw  new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        String redisCode  =(String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (StringUtils.isBlank(redisCode)){
            throw  new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!loginVo.getCaptchaCode().equalsIgnoreCase(redisCode)){
            throw  new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //2. 验证账号
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(lambdaQueryWrapper);
        if (systemUser == null){
            throw  new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        //3. 验证密码
        String md5Password = DigestUtils.md5Hex(loginVo.getPassword());
        if (!md5Password.equals(systemUser.getPassword())){
            throw  new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //4. 验证账号状态
        if (systemUser.getStatus() == BaseStatus.DISABLE ){
            throw  new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //5. 生成token (jwt)
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());

        return token;
    }

    @Override
    public SystemUserInfoVo info(String accountToken) {

        String username = ThreadLocalUtils.get();
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,username);
        SystemUser systemUser = systemUserService.getOne(lambdaQueryWrapper);

        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
